<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--需求信息-->
			<view class="detail-item">
				<uni-section title="需求信息" type="line"></uni-section>
				<view class="detail-content">
					<view class="detail-text">
						需求编号：
						<text>{{info.number}}</text>
						<text class="detail-text-copy" @click="copyText(info.number)">复制</text>
					</view>
					<view class="detail-text">配送仓：<text>{{info.warehouseName}}</text></view>
					<view class="detail-text">区域代码：<text>{{info.regionCode}}</text></view>
					<view class="detail-text">分拣仓：<text>{{info.fenjianWarehouseName}}</text></view>
					<view class="detail-text">制单时间：<text>{{info.createTime}}</text></view>
					<view class="detail-text">审核时间：<text>{{info.confirmTime}}</text></view>
					<view class="detail-text">执行时间：<text>{{info.executeTime}}</text></view>
					<view class="detail-text">销需状态：<uni-tag size="small" :text="arrText(allStatusList, info.status)" /></view>
					<view class="detail-text">
						销需说明：
						<text>{{info.remark}}</text>
						<text class="detail-text-copy" @click="copyText(info.remark)">复制</text>
					</view>
				</view>
			</view>
			
			<!--需求商品-->
			<view class="detail-item">
				<uni-section title="需求商品" type="line"></uni-section>
				<!-- <view class="detail-form">
					<uni-forms ref="searchRef" label-width="160rpx">
						<uni-forms-item label="商品类型">
							<uni-data-select
								v-model="purchaseDemandWarehouseId"
								placeholder="请选择商品类型"
								@change="changeWarehouse"
								:localdata="purchaseDemandWarehouseList"></uni-data-select>
						</uni-forms-item>
					</uni-forms>
				</view> -->
				<view class="detail-content table">
					<ty-table
						:data="demandProductTableList"
						:columns="demandProductColumns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						stripe
						border>
						<template v-slot:before="{ row }">
							<view class="table-td-before table-cell table-td-row">
								<view class="table-td-row">
									序号：
									<text class="table-td-text">{{row.rowIndex + 1}}</text></view>
								<view class="table-td-row">
									商品名称：
									<text class="table-td-text">{{row.productName}}</text></view>
								<view class="table-td-row">
									商品编码：
									<text class="table-td-text">{{row.productCode}}</text></view>
								<view class="table-td-row">
									规格：
									<text class="table-td-text">{{row.productUnit}}</text></view>
							</view>
						</template>
						<template v-slot:demandNumber="{ row }">
							<view class="table-td-cell">
								<uni-easyinput v-model="row.demandNumber" :disabled="!(info.status==0)" @blur="demandChange($event, row)" type="number" placeholder="请输入需求数量" />
							</view>
						</template>
						<template v-slot:remark="{ row }">
							<view class="table-td-cell">
								<uni-easyinput v-model="row.remark" :disabled="!(info.status==0)" @blur="demandChange($event, row)" placeholder="请输入备注" />
							</view>
						</template>
						<template v-slot:status="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row">
									<uni-tag size="small" :type="row.status === 1 ? 'success' : ''" :text="arrText(salesmanDemandProductStatusList, row.status === 1 ? 1 : 0)" /></view>
							</view>
						</template>
					</ty-table>
				</view>
				<view class="submit main-flex">
					<button type="primary" class="submit-item" :disabled="isSubmit1" :loading="isSubmit1" @click="submit1()">暂存</button>
					<button type="primary" class="submit-item" :disabled="isSubmit2" :loading="isSubmit2" @click="submit2()">提交</button>
				</view>
			</view>
			
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { 
	salesmanDemandAdd,
	salesmanDemandDetail,
	salesmanDemandProduct,
	salesmanDemandProductAdd } from "@/api/erp_api/sale"
import { salesmanDemandStatus } from "@/api/system/dict/data"
import { productType } from "@/api/erp_api/product"
import { allProvince } from "@/api/erp_api/region"
import { upload } from "@/api/system/common"
import { copyText, arrText } from '@/utils/ty.js'
import { salesmanDemandProductStatusList } from '@/utils/config.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad(async (option) => {
		await getSalesmanDemandStatus()
		if (option.id) {
			uni.setNavigationBarTitle({
				title: '修改销售需求'
			})
			id.value = option.id
			getDetail()
			searchFirst()
		}
	})
	
	// 销售需求状态
	const allStatusList = ref([])
	const getSalesmanDemandStatus = () => {
		return salesmanDemandStatus().then(res => {
			allStatusList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		// isLoading.value = true
		// uni.showLoading({
		// 	title: '数据加载中...'
		// })
		salesmanDemandDetail(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				customerName: res.data.customerName,
				phone: res.data.phone,
				regionCode: res.data.regionCode,
				storeName: res.data.storeName,
				storeImag: res.data.storeImag,
				addr: res.data.addr,
				addrDetail: res.data.addrDetail,
				level: res.data.level,
				lng: res.data.lng,
				lat: res.data.lat,
				isPublic: res.data.isPublic
			}
			fileList.value = res.data.storeImag ? res.data.storeImag.split(',').map(item => {
				return {
					status: 'success',
					message: '上传成功',
					url: item,
					type: 'image'
				}
			}) : []
			// isLoading.value = false
			// uni.hideLoading()
	  }).catch(() => {
			// isLoading.value = false
			// uni.hideLoading()
		})
	}
	
	// 选择类型
	const purchaseDemandWarehouseId = ref('')
	const changeWarehouse = (val) => {
		if (val) {
			getWarehouseProduct(val)
		} else {
			warehouseProductTableList.value = []
		}
	}
	
	// 需求商品
	const demandProductColumns = ref([
		{ title: '需求数量', key: 'demandNumber' },
		{ title: '备注', key: 'remark' },
		{ title: '状态', key: 'status', width: '120rpx' }
	])
	
	const pageNum = ref(1)
	const pageSize = ref(1000)
	const total = ref(0)
	const demandProductTableList = ref([])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		demandProductTableList.value = []
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			salesmanDemandId: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanDemandProduct(params).then(res => {
			demandProductTableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	const demandChange = (e, row) => {
		demandProductTableList.value[row.rowIndex] = {...row}
	}
	
	const isSubmit1 = ref(false)
	const isSubmit2 = ref(false)
	// 暂存
	const submit1 = () => {
		const list = demandProductTableList.value.filter(item => item.demandNumber || item.remark).map(item => {
			delete item.rowIndex
			return {
				...item,
				salesmanDemandId: item.salesmanDemandId ? item.salesmanDemandId : id.value
			}
		})
		if (list.length === 0) {
			modal.showToast('请填写商品清单')
			return false
		}
		isSubmit1.value = true
		salesmanDemandProductAdd(list).then(async (res) => {
			modal.showToast(res.msg)
			await uni.$u.sleep(1000)
			isSubmit1.value = false
			getList()
		}).catch(err => {
			isSubmit1.value = false
		})
	}
	// 提交
	const submit2 = (type) => {
		isSubmit2.value = true
		salesmanDemandAdd({
			id: id.value,
			status: 1
		}).then(async (res) => {
			modal.showToast(res.msg)
			await uni.$u.sleep(1000)
			isSubmit2.value = false
			uni.$emit('refreshList');  // 触发刷新事件
			uni.navigateBack({
				delta: 1
			})
		}).catch(err => {
			isSubmit2.value = false
		})
	}
</script>

<style scoped lang="scss">
	.content {
		padding-bottom: calc(env(safe-area-inset-bottom) + 118rpx);
	}
	.submit {
		position: fixed;
		width: 100%;
		left: 0;
		bottom: 0;
		padding: 20rpx 20rpx calc(env(safe-area-inset-bottom) + 20rpx);
		background-color: #ffffff;
		&-item {
			width: 300rpx;
			height: 96rpx;
		}
	}
</style>
